const Service = require('egg').Service

class MenuRoleService extends Service {
	constructor(ctx) {
		super(ctx)
	}
	async index() {
		const data = await this.ctx.model.Menu.findAll({
			plain: false,
			raw: true,
		})
		const newData = {
			admin: data,
			author: data,
			user: data,
		}
		newData.admin = this.ctx.helper.toTree(
			data.map(menu => {
				if (JSON.parse(menu.roleLevel).includes(3)) {
					return {
						...menu,
						status: 1,
					}
				} else {
					return {
						...menu,
						status: 0,
					}
				}
			})
		)
		newData.author = this.ctx.helper.toTree(
			data.map(menu => {
				if (JSON.parse(menu.roleLevel).includes(2)) {
					return {
						...menu,
						status: 1,
					}
				} else {
					return {
						...menu,
						status: 0,
					}
				}
			})
		)
		newData.user = this.ctx.helper.toTree(
			data.map(menu => {
				if (JSON.parse(menu.roleLevel).includes(1)) {
					return {
						...menu,
						status: 1,
					}
				} else {
					return {
						...menu,
						status: 0,
					}
				}
			})
		)
		return {
			status: 'success',
			data: newData,
		}
	}

	async update(id, body) {
		const roleType = {
			admin: 3,
			author: 2,
			user: 1,
		}
		const { role, status } = body
		const menu = await this.ctx.model.Menu.findOne({
			raw: true,
			where: { id },
		})
		let roles = JSON.parse(menu.roleLevel)
		if (status) {
			roles.push(roleType[role])
		} else {
			roles = roles.filter(item => item !== roleType[role])
		}
		await this.ctx.model.Menu.update(
			{
				roleLevel: JSON.stringify(roles),
			},
			{ where: { id } }
		)
		return 'success'
	}
}

module.exports = MenuRoleService
